<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
// import Joomla modelform library
jimport('joomla.application.component.modeladmin');
 
/**
 * HelloWorld Model
 */
class ProductsModelProduct extends JModelAdmin
{
	//文件扩展名
	public function fileext($filename) {
		return trim(substr(strrchr($filename, '.'), 1));
	}
	//文件信息
	public function getInfo($file) { 
		$data = getimagesize($file);
		$imageInfo["width"] = $data[0]; 
		$imageInfo["height"]= $data[1]; 
		$imageInfo["type"] = $data[2]; 
		$imageInfo["name"] = basename($file);
		$imageInfo["size"] = filesize($file);
		return $imageInfo; 
	} 
	/*
	 * 图片上传
	*/
	public function uploadfile($file){
		static $imgext  = array('jpg', 'jpeg', 'gif', 'png', 'bmp');
		$ext=strtolower($this->fileext($file['name']));
		if(!in_array($ext, $imgext)) {
			$response = array(
				'status' => '0',
				'error' => "请上传图片类型文件（.jpg .jpeg .gif .png .bmp）"
			);
			echo json_encode($response);
			return;
		}
		
		$img_name=date('Ymdhis').'.'.$ext;//文件新命名
		$filepath=COM_MEDIA_BASE.$img_name;			
		if (!move_uploaded_file($file['tmp_name'], $filepath)){
		//if (!JFile::upload($file['tmp_name'], $filepath)){			
			$response = array(
				'status' => '0',
				'error' => JText::_('COM_MEDIA_ERROR_UNABLE_TO_UPLOAD_FILE')
			);
			echo json_encode($response);
			return;
		}
		//echo $filepath;exit;
		$max_width=$max_height=800;//图片最大长，宽	
		$imageInfo = $this->getInfo($filepath); 
		$photox = $imageInfo['width'];//长
		$photoy = $imageInfo['height'];//宽		
		if($photox>$max_width || $photoy>$max_height){
			//如果图片过大，需要缩略。	
			//$this->imgsize($filepath,'',$max_width,$max_height,2);	//$action==2 修改原图
			$new_img=$this->makeThumb($filepath,'',$max_width,$max_height,'0');			
		}
		
		return $img_name;
	}
	/*
	* 函数: makeThumb($sourFile,$width=128,$height=128) 
	* 功能: 生成缩略
	* 参数: $sourFile 图片源文件 
	* 参数: $width 生成缩略图的宽度 
	* 参数: $height 生成缩略图的高度 
	* 返回: 0 失败 成功时返回生成的图片路径 
	*/
	public function makeThumb($sourFile='', $subdir='', $width=350, $height=350,$action=1) { 
		$attachdir=COM_MEDIA_BASE;
		$imageInfo = $this->getInfo($sourFile); 
		if ($action==1){
			//新建
			$newName = substr($imageInfo["name"], 0, strrpos($imageInfo["name"], ".")) . "_s.jpg";
		}else{
			//覆盖
			$newName = $imageInfo["name"]; 
		}
		
		switch ($imageInfo["type"]) { 
			case 1: //gif 
				$img = imagecreatefromgif($sourFile); 
				break; 
			case 2: //jpg 
				$img = imagecreatefromjpeg($sourFile); 
				break; 
			case 3: //png 
				$img = imagecreatefrompng($sourFile); 
				break; 
			default: 
				return 0; 
				break; 
		} 
		if (!$img) return 0; 
	
		$width = ($width > $imageInfo["width"]) ? $imageInfo["width"] : $width; 
		$height = ($height > $imageInfo["height"]) ? $imageInfo["height"] : $height; 
	
		$srcW = $imageInfo["width"]; 
		$srcH = $imageInfo["height"]; 
		if ($srcW * $width > $srcH * $height) {
			$height = round($srcH * $width / $srcW); 
		} else { 
			$width = round($srcW * $height / $srcH); 
		}
	
		if (function_exists("imagecreatetruecolor")){ //GD2.0.1  
			$new = imagecreatetruecolor($width, $height); 
			
			//如果是gif图片，赋值一个白色背景
			if ($imageInfo["type"]==1){
				$background = imagecolorallocate($new, 255, 255, 255);
				imagefilledrectangle($new, 0, 0 ,$width, $height, $background); 
			}
	
			ImageCopyResampled($new, $img, 0, 0, 0, 0, $width, $height, $imageInfo["width"], $imageInfo["height"]); 
		} else { 
			$new = imagecreate($width, $height); 
			ImageCopyResized($new, $img, 0, 0, 0, 0, $width, $height, $imageInfo["width"], $imageInfo["height"]); 
		}
		
		$thumburl = $subdir ? $attachdir.'/'.$subdir.'/'.$newName : $attachdir.'/'.$newName;
		$returnurl = $subdir ? $subdir.'/'.$newName : $newName;
	
		if (file_exists($newName)) unlink($thumburl); 
		ImageJPEG($new, $thumburl); 		
		return $returnurl; 
		ImageDestroy($new); 
		ImageDestroy($img); 
	}
	
	
	public function save($data){
		
		$file   = JRequest::getVar( 'Filedata', '', 'files', 'array' );
		if (!empty($file)){
			$image=$this->uploadfile($file);
			$thumb_width=$thum_height='160';
			$thumbnail=$this->makeThumb(COM_MEDIA_BASE.$image,'',$thumb_width,$thum_height);	
		}
		
		if ($image){
			$data['img']=$image;
			$data['thumbnail']=$thumbnail;
		}
		
		$user = JFactory::getUser();		
		$date_now=date('Y-m-d H:i:s',time());
		if ($data['id']==0){
			//新建
			$data['created_date']=$date_now;
			$data['creater_id']=$user->id;
		}
		
		$data['updated_date']=$date_now;
		$data['updater_id']=$user->id;
		
		//print_r($data);exit;
		if (parent::save($data)){
			return true;
		}
	}
	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @param	string	A prefix for the table class name. Optional.
	 * @param	array	Configuration array for model. Optional.
	 * @return	JTable	A database object
	 * @since	1.6
	 */
	public function getTable($type = 'Product', $prefix = 'ProductTable', $config = array()) 
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	/**
	 * Method to get the record form.
	 *
	 * @param	array	$data		Data for the form.
	 * @param	boolean	$loadData	True if the form is to load its own data (default case), false if not.
	 * @return	mixed	A JForm object on success, false on failure
	 * @since	1.6
	 */
	public function getForm($data = array(), $loadData = true) 
	{
		// Get the form.
		$form = $this->loadForm('com_products.products', 'products', array('control' => 'jform', 'load_data' => $loadData));
		if (empty($form)) 
		{
			return false;
		}
		return $form;
	}
	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return	mixed	The data for the form.
	 * @since	1.6
	 */
	protected function loadFormData() 
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState('com_products.edit.product.data', array());
		if (empty($data)) 
		{
			$data = $this->getItem();
		}
		return $data;
	}
	public function delete($itemIds)
	{
		// Sanitize the ids.
		$itemIds = (array) $itemIds;
		JArrayHelper::toInteger($itemIds);

		// Get a group row instance.
		$table = $this->getTable();

		// Iterate the items to delete each one.
		foreach ($itemIds as $itemId) {
			// TODO: Delete the menu associations - Menu items and Modules

			if (!$table->delete($itemId))
			{
				$this->setError($table->getError());
				return false;
			}
		}

		// Clean the cache
		$this->cleanCache();

		return true;
	}
	public function featured($data){
		if (parent::save($data)){
			return true;
		}
	}
}
